package com.xingkeduo.service.cms.marketing.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.xingkeduo.dao.TMarketingReleaseHistoryMapper;
import com.xingkeduo.feign.ManageUserFeignService;
import com.xingkeduo.feign.MarketingFeignService;
import com.xingkeduo.feign.MessageFeignService;
import com.xingkeduo.feign.OperationFeignService;
import com.xingkeduo.model.example.TMarketingReleaseHistoryExample;
import com.xingkeduo.model.example.TMarketingReleaseHistoryExample.Criteria;
import com.xingkeduo.model.param.marketing.MarketingReleaseHistoryParam;
import com.xingkeduo.model.po.TMarketingReleaseHistoryWithBLOBs;
import com.xingkeduo.model.vo.TMarketingReleaseHistoryResponseVo;
import com.xingkeduo.service.cms.marketing.MarketingReleaseService;
import com.xingkeduo.util.Constant;
import com.xingkeduo.util.DateUtils;
import com.xingkeduo.util.tool.ResponseMessage;

@Service
public class MarketingReleaseServiceImpl implements MarketingReleaseService {
	Logger logger = LoggerFactory.getLogger(MarketingReleaseServiceImpl.class);

	@Autowired
	TMarketingReleaseHistoryMapper tMarketingReleaseHistoryMapper;
	@Autowired
	MarketingFeignService marketingFeignService;
	@Autowired
	MessageFeignService messageFeignService;
	@Autowired
	OperationFeignService operationFeignService;
	@Autowired
	ManageUserFeignService manageUserFeignService;

	@Override
	public ResponseMessage getCustormerServiceReleaseList(MarketingReleaseHistoryParam releaseTemplateExample) {
		TMarketingReleaseHistoryExample example = new TMarketingReleaseHistoryExample();
		Criteria criteria = example.createCriteria();
		criteria.andStatusEqualTo(Constant.STATUS_YES);
		if (releaseTemplateExample.getUserId() != null) {
			criteria.andCreateByEqualTo(releaseTemplateExample.getUserId());
		}
		if (StringUtils.isNotBlank(releaseTemplateExample.getStartDate())) {
			criteria.andCreateTimeGreaterThanOrEqualTo(DateUtils.parseDate(releaseTemplateExample.getStartDate()));
		}
		if (StringUtils.isNotBlank(releaseTemplateExample.getEndDate())) {
			criteria.andCreateTimeLessThanOrEqualTo(DateUtils.parseDate(releaseTemplateExample.getEndDate()));
		}
		example.setOrderByClause(" id desc");
		PageHelper.startPage(releaseTemplateExample.getPageNum(), releaseTemplateExample.getPageSize());
		List<TMarketingReleaseHistoryWithBLOBs> tMarketingReleaseHistoryList = tMarketingReleaseHistoryMapper
				.selectByExampleWithBLOBs(example);
		PageInfo<TMarketingReleaseHistoryWithBLOBs> page = new PageInfo<>(tMarketingReleaseHistoryList);
		PageInfo<TMarketingReleaseHistoryResponseVo> pageReturn = new PageInfo<>();
		BeanUtils.copyProperties(page, pageReturn);
		List<TMarketingReleaseHistoryResponseVo> returnList = Lists.transform(tMarketingReleaseHistoryList,
				new Function<TMarketingReleaseHistoryWithBLOBs, TMarketingReleaseHistoryResponseVo>() {
					@Override
					public TMarketingReleaseHistoryResponseVo apply(TMarketingReleaseHistoryWithBLOBs history) {
						TMarketingReleaseHistoryResponseVo responseVo = new TMarketingReleaseHistoryResponseVo();
						BeanUtils.copyProperties(history, responseVo);
						String result = manageUserFeignService.queryUserByNameOrMobileOrId("{\"condition\":\"" + history.getUserId() + "\"}");
						JSONObject userListJson = JSON.parseObject(result);
						logger.info("userListJson:" + userListJson);
						String resultStatus = userListJson.getOrDefault("status", "0") == null ? "0"
								: userListJson.getOrDefault("status", "0").toString();
						if (resultStatus.equals("1")) {
							JSONArray resultDataArray = userListJson.getJSONArray("data");
							if (resultDataArray != null && (!resultDataArray.isEmpty())) {
								int size = resultDataArray.size();
								for (int i = 0; i < size; i++) {
									JSONObject resultData = resultDataArray.getJSONObject(i);
									String oldUserId = resultData.getOrDefault("id", "0") == null ? "0"
											: resultData.getOrDefault("id", "0").toString();
									if (history.getUserId().equals(Long.parseLong(oldUserId))) {
										String name = resultData.getOrDefault("name", "") == null ? "" : resultData.getOrDefault("name", "").toString();
										responseVo.setUserInfo(oldUserId+"_"+name);
										String phone = resultData.getOrDefault("phone", "") == null ? "" : resultData.getOrDefault("phone", "").toString();
										responseVo.setUserMobile(phone);
									}
								}
							}
						}
						if (StringUtils.isNotBlank(responseVo.getReleaseData())) {
							int cardCount = 0;
							StringBuffer cardBuffer = new StringBuffer();
							int couponCount = 0;
							StringBuffer couponBuffer = new StringBuffer();
							JSONArray array = JSONArray.parseArray(responseVo.getReleaseData());
							int size = array.size();
							for (int i = 0; i < size; i++) {
								JSONObject json = array.getJSONObject(i);
								String marketingType = json.getOrDefault("marketingType", "0") == null ? "0"
										: json.getOrDefault("marketingType", "0").toString();
								String marketingName = json.getOrDefault("servprodName", "") == null ? ""
										: json.getOrDefault("servprodName", "").toString();
								String totalQuantity = json.getOrDefault("totalQuantity", "0") == null ? "0"
										: json.getOrDefault("totalQuantity", "0").toString();
								if ("0".equalsIgnoreCase(marketingType)) { // 券
									// 发放数量维护
									couponCount = couponCount + Integer.parseInt(totalQuantity);
									// 发放券卡名称维护
									if (StringUtils.isBlank(couponBuffer.toString())) {
										couponBuffer.append(marketingName);
									}else if(!couponBuffer.toString().endsWith(" 等")) {
										couponBuffer.append(" 等");
									}
								} else {
									// 发放数量维护
									cardCount = cardCount + Integer.parseInt(totalQuantity);
									// 发放券卡名称维护
									if (StringUtils.isBlank(cardBuffer.toString())) {
										cardBuffer.append(marketingName);
									}else if(!cardBuffer.toString().endsWith(" 等")) {
										cardBuffer.append(" 等");
									}
								}
							}
							if(StringUtils.isNotBlank(couponBuffer.toString())) {
								responseVo.setCouponMemo(couponBuffer.toString()+couponCount+"张");
							}
							if(StringUtils.isNotBlank(cardBuffer.toString())) {
								responseVo.setCardMemo(cardBuffer.toString()+cardCount+"张");
							}
						}
						return responseVo;
					}
				});
		pageReturn.setList(returnList);
		return ResponseMessage.ok(pageReturn);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
	public ResponseMessage addMarketingRelease(MarketingReleaseHistoryParam releaseTemplateExample) {
		if (releaseTemplateExample.getCreateBy() != null) {
			String manager = operationFeignService.getManager("{\"id\":" + releaseTemplateExample.getCreateBy() + "}");
			JSONObject managerJson = JSON.parseObject(manager);
			String resultStatus = managerJson.getOrDefault("status", "0") == null ? "0"
					: managerJson.getOrDefault("status", "0").toString();
			if (resultStatus.equals("0")) {
				return ResponseMessage.error("发券用户解析失败", 500);
			}
			JSONObject resultData = managerJson.getJSONObject("data");
			if (resultData == null) {
				return ResponseMessage.error("发券用户解析失败", 500);
			}
			String manageName = resultData.getOrDefault("name", "") == null ? ""
					: resultData.getOrDefault("name", "").toString();
			releaseTemplateExample.setCreateName(manageName);
		}

		TMarketingReleaseHistoryWithBLOBs history = new TMarketingReleaseHistoryWithBLOBs();
		BeanUtils.copyProperties(releaseTemplateExample, history);
		history.setStatus(Constant.STATUS_YES);
		history.setCreateTime(new Date());
		int count = tMarketingReleaseHistoryMapper.insertSelective(history);
		if (count == 0) {
			return ResponseMessage.error("发送失败", 500);
		}
		String resultJson = marketingFeignService.bindBatchReceiveAccount(releaseTemplateExample.getUserId(),
				releaseTemplateExample.getReleaseData());
		JSONObject jsonData = JSON.parseObject(resultJson);
		String status = jsonData.getOrDefault("status", "0") == null ? "0"
				: jsonData.getOrDefault("status", "0").toString();
		if ("0".equals(status)) {
			throw new RuntimeException(
					jsonData.getOrDefault("msg", "") == null ? "" : jsonData.getOrDefault("msg", "").toString());
		}
		try {
			JSONArray array = jsonData.getJSONArray("data");
			int size = array.size();
			if (array != null && size > 0) {
				JSONObject jsonObject = array.getJSONObject(0);
				String couponName = jsonObject.getOrDefault("marketingName", "") == null ? ""
						: jsonObject.getOrDefault("marketingName", "").toString();
				String num = "0";
				String releaseData = releaseTemplateExample.getReleaseData();
				JSONArray releaseArray = JSONArray.parseArray(releaseData);
				if(releaseArray!=null && !releaseArray.isEmpty()) {
					JSONObject releaseJson = releaseArray.getJSONObject(0);
					num = releaseJson.getOrDefault("totalQuantity", "0")==null ? "0":releaseJson.getOrDefault("totalQuantity", "0").toString();
				}
				if (size > 1) {
					couponName = couponName + "等";
				}
				Date useStartTime = jsonObject.getDate("useStartTime");
				String couponUseStartTime = useStartTime == null ? ""
						: DateUtils.formatDate(useStartTime, DateUtils.DATE_FORMAT_V2);
				Date useEndTime = jsonObject.getDate("useEndTime");
				String couponUseEndTime = useEndTime == null ? ""
						: DateUtils.formatDate(useStartTime, DateUtils.DATE_FORMAT_V2);
				messageFeignService.pushSendSuccessMessage(releaseTemplateExample.getUserId().toString(), couponName,
						couponUseStartTime, couponUseEndTime,Long.parseLong(num));
			}
		} catch (Exception e) {
			logger.info("消息推送失败");
		}

		return ResponseMessage.ok();
	}
	
	public static void main(String[] args) {
		String releaseData = "[]";
		String num = "0";
		JSONArray releaseArray = JSONArray.parseArray(releaseData);
		if(releaseArray!=null && !releaseArray.isEmpty()) {
			JSONObject releaseJson = releaseArray.getJSONObject(0);
			num = releaseJson.getOrDefault("totalQuantity", "0")==null ? "0":releaseJson.getOrDefault("totalQuantity", "0").toString();
		}
		System.out.println(num);
	}

	@Override
	public ResponseMessage getCustormerServiceReleaseDetail(Long marketingReleaseHistoryId) {
		TMarketingReleaseHistoryWithBLOBs history = tMarketingReleaseHistoryMapper
				.selectByPrimaryKey(marketingReleaseHistoryId);
		TMarketingReleaseHistoryResponseVo responseVo = new TMarketingReleaseHistoryResponseVo();
		BeanUtils.copyProperties(history, responseVo);
		String result = manageUserFeignService.queryUserByNameOrMobileOrId("{\"condition\":\"" + history.getUserId() + "\"}");
		JSONObject userListJson = JSON.parseObject(result);
		logger.info("userListJson:" + userListJson);
		String resultStatus = userListJson.getOrDefault("status", "0") == null ? "0"
				: userListJson.getOrDefault("status", "0").toString();
		if (resultStatus.equals("1")) {
			JSONArray resultDataArray = userListJson.getJSONArray("data");
			if (resultDataArray != null && (!resultDataArray.isEmpty())) {
				int size = resultDataArray.size();
				for (int i = 0; i < size; i++) {
					JSONObject resultData = resultDataArray.getJSONObject(i);
					String oldUserId = resultData.getOrDefault("id", "0") == null ? "0"
							: resultData.getOrDefault("id", "0").toString();
					if (history.getUserId().equals(Long.parseLong(oldUserId))) {
						String name = resultData.getOrDefault("name", "") == null ? "" : resultData.getOrDefault("name", "").toString();
						responseVo.setUserInfo(oldUserId+"_"+name);
						String phone = resultData.getOrDefault("phone", "") == null ? "" : resultData.getOrDefault("phone", "").toString();
						responseVo.setUserMobile(phone);
					}
				}
			}
		}
		return ResponseMessage.ok(responseVo);
	}

}
